package gui

import (
	"log"
	"os"
	"path/filepath"
	"strings"
	theme2 "wxp2p/uiapp/theme"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
	"github.com/atotto/clipboard"
)

func settingsWindow(gVars *GlobalVars) fyne.CanvasObject {
	myApp := gVars.APP
	// 主题
	dropdown := widget.NewSelect([]string{"Light", "Dark"}, parseTheme())
	t := gVars.APP.Preferences().StringWithFallback("Theme", "Light")
	switch t {
	case "Light":
		dropdown.PlaceHolder = "Light"
	case "Dark":
		dropdown.PlaceHolder = "Dark"
	}
	dropdown.Refresh()
	themeRow := container.NewBorder(nil, nil, canvas.NewText("主题切换", nil), nil, dropdown)
	// 信令服务器地址
	gVars.signalAddr = gVars.APP.Preferences().StringWithFallback("signalAddr", "43.138.80.3:8018")
	sigAddrEntry := widget.NewEntry()
	sigAddrEntry.SetText(gVars.signalAddr)
	sigAddrEntry.OnChanged = func(s string) {
		gVars.signalAddr = s
		gVars.APP.Preferences().SetString("signalAddr", s)
	}
	sigRow := container.NewBorder(nil, nil, canvas.NewText("信令服务器", nil), nil, sigAddrEntry)
	// 本机识别码
	gVars.localClientId = myApp.Preferences().StringWithFallback("clientId", genClientId())
	localClientIdEntry := widget.NewEntry()
	localClientIdEntry.SetText(gVars.localClientId)
	localClientIdEntry.Disable()
	startOffer := widget.NewButtonWithIcon("复制", theme.ContentCopyIcon(), func() {
		clipboard.WriteAll(gVars.localClientId)
	})
	// 启动服务
	gVars.server.StopRun()
	gVars.server.ServerAddr = gVars.signalAddr
	gVars.server.ClientId = gVars.localClientId
	gVars.server.Run()

	clientIdRow := container.NewBorder(nil, nil, canvas.NewText("本机识别码", nil), startOffer, localClientIdEntry)
	// 本地接收文件目录
	fileLocate := myApp.Preferences().StringWithFallback("recvfilepath", getCurrentDirectory())
	fileEntry := widget.NewEntry()
	fileEntry.SetText(fileLocate)
	fileLocateRow := container.NewBorder(nil, nil, canvas.NewText("接收文件目录", nil), nil, fileEntry)

	settings := container.NewVBox(themeRow, sigRow, clientIdRow, fileLocateRow)
	return settings
}

func parseTheme() func(string) {
	return func(t string) {
		switch t {
		case "Light":
			fyne.CurrentApp().Preferences().SetString("Theme", "Light")
			fyne.CurrentApp().Settings().SetTheme(&theme2.MyTheme{Theme: "Light"})
		case "Dark":
			fyne.CurrentApp().Preferences().SetString("Theme", "Dark")
			fyne.CurrentApp().Settings().SetTheme(&theme2.MyTheme{Theme: "Dark"})
		}
	}
}

func getCurrentDirectory() string {
	//返回绝对路径  filepath.Dir(os.Args[0])去除最后一个元素的路径
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		log.Println(err)
	}

	//将\替换成/
	return strings.Replace(dir, "\\", "/", -1)
}
